package com.cw.wizbank.synchronous;

import java.io.File;
import java.util.List;

import org.apache.log4j.Logger;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;


public class ZipHelper {
	
	static final String CHARSET_UTF8 = "UTF-8";
	static final String CHARSET_GBK = "GBK";
	Logger successLog = Logger.getLogger("Synchronous_Data_Success_Peofile");
	Logger errorLog = Logger.getLogger("Synchronous_Data_Err_Profile");
	/**
	 * 解压zip文件
	 * @param zipFile   	文件名
	 * @param outFileDir	解压地址
	 * @param pwd			密码
	 * @throws ZipException
	 */
	public void Unzip4j(String zipFile, String outFileDir, String pwd) throws ZipException {
		ZipFile zip = new ZipFile(zipFile);
		long startTime = System.currentTimeMillis();
		// 第一时间设置编码格式
		zip.setFileNameCharset(CHARSET_UTF8);
		System.out.println(zipFile);
		successLog.info("+++zipFile="+zipFile+"++++");
		// 用自带的方法检测一下zip文件是否合法，包括文件是否存在、是否为zip文件、是否被损坏等
		if (!zip.isValidZipFile()) {
			errorLog.error("文件不合法或不存在");
			throw new ZipException("文件不合法或不存在");
		}
		checkEncrypted(zip);
		if (zip.isEncrypted()) {
			zip.setPassword(pwd);
		}
		// 跟java自带相比，这里文件路径会自动生成，不用判断
		zip.extractAll(outFileDir);
		System.out.println(outFileDir);
		System.out.println("解压成功！");
		successLog.info("解压成功！");
		long endTime = System.currentTimeMillis();
		System.out.println("耗时：" + (endTime - startTime) + "ms");
		successLog.info("耗时：" + (endTime - startTime) + "ms");
	}

	// 解压方法2
	public void Unzip4j1(String zipFile) throws ZipException {
		long startTime = System.currentTimeMillis();
		ZipFile zipFile2 = new ZipFile(zipFile);
		// 设置编码格式
		zipFile2.setFileNameCharset(CHARSET_GBK);
		if (!zipFile2.isValidZipFile()) {
			errorLog.error("文件不合法或不存在");
			throw new ZipException("文件不合法或不存在");
		}
		// 检查是否需要密码
		checkEncrypted(zipFile2);
		List<FileHeader> fileHeaderList = zipFile2.getFileHeaders();
		for (int i = 0; i < fileHeaderList.size(); i++) {
			FileHeader fileHeader = fileHeaderList.get(i);
			zipFile2.extractFile(fileHeader, "D:\\压缩\\test");
		}
		System.out.println("解压成功！");
		long endTime = System.currentTimeMillis();
		System.out.println("耗时：" + (endTime - startTime) + "ms");
	}

	// 检测密码
	private void checkEncrypted(ZipFile zip) throws ZipException {
		if (zip.isEncrypted()) {
			System.out.println("文件" + zip.getFile().getName() + "有密码！");
			zip.setPassword("9527");
		}
	}

	public static void main(String[] args) throws ZipException {
		ZipHelper demo = new ZipHelper();
		//demo.Unzip4j1("D:\\demo.zip");
		demo.Unzip4j("C:/Users/lenovo/Desktop/watstons/629/wtc_accountsynch_20180701.zip", "C:/Users/lenovo/Desktop/watstons/629", "bee");
	}
}
